package com.epfresh.supplier.activity.employ;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.AuthEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by shenjie on 2017/9/14.
 */

public class AddEmployActivity extends BaseActivity {
    private RelativeLayout setAuth;
    private EditText name, phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Constant.posLists = null;
        Constant.wholeSaleLists = null;
        initView();
        try {
            parseResources();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        toolbarTitle.setText("新增员工");
        toolbarTitle.setTextColor(getResources().getColor(R.color.font_color_def));
        float textsize = getResources().getDimension(R.dimen.text_size_max_18);
        final float scale = getResources().getDisplayMetrics().density;
        float size = (textsize / scale + 0.5f);
//        toolbarTitle.setTextSize(size);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        rightbtn.setText("保存");
//        rightbtn.setTextSize( getResources().getDimension(R.dimen.text_size_mid_16)/scale + 0.5f);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setTextColor(getResources().getColor(R.color.red));
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (InputControl.isEmpty(name)) {
                    T.toast("请输入员工姓名");
                    return;
                }
                if (name.getText().toString().trim().length() > 10) {
                    T.toast("姓名长度不能超过10");
                    return;
                }
                if (InputControl.isEmpty(phone)) {
                    T.toast("请输入员工手机号码");
                    return;
                }
                if (!isNumeric(phone.getText().toString().trim())) {
                    T.toast("手机号码不能包含非数字字符");
                    return;
                }
                if (phone.getText().toString().trim().length() != 11) {
                    T.toast("手机号码必须为11位");
                    return;
                }
                loadHttp();
            }
        });
        setContentView(R.layout.activity_add_employ);
        name = (EditText) findViewById(R.id.name_et);
        phone = (EditText) findViewById(R.id.phone_et);
        setAuth = (RelativeLayout) findViewById(R.id.setauth);
        setAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddEmployActivity.this, AuthSettingActivity.class);
                startActivity(intent);
            }
        });
    }


    private void loadHttp() {
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_account_employee_add);
        //data.setCmd("account/employee/add");
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", getUser().getAccountId());
        map.put("merchantId", getAppApplication().getMerchantId());
        map.put("name", name.getText().toString().trim());
        map.put("phone", phone.getText().toString().trim());
        HashMap<String, Boolean> resources = new HashMap<>();
        if (Constant.posLists != null) {
            for (AuthEntity entity : Constant.posLists) {
                if (entity.getMenu() == 2 && entity.isHasAuth()) {
                    resources.put(entity.getId(), Boolean.TRUE);
                }
            }
        }
        if (Constant.wholeSaleLists != null) {
            for (AuthEntity entity : Constant.wholeSaleLists) {
                if (entity.getMenu() == 2 && entity.isHasAuth()) {
                    resources.put(entity.getId(), Boolean.TRUE);
                }
            }
        }
        map.put("resources", resources);

        data.setParameters(map);
        request(data, AppSupplyRouterConstant.cmd_account_employee_add, onRequestListener);
    }


    private OnRequestListener<String> onRequestListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            hideProgressDialog();
            T.toast("新增员工成功");
            setResult(100);
            finish();
        }
    };

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    private void parseResources() throws JSONException {
        if(TextUtils.isEmpty(Constant.resourcesStr)){
            return;
        }
        ArrayList<AuthEntity> posLists;
        ArrayList<AuthEntity> wholeSaleLists;

        JSONObject object = new JSONObject(Constant.resourcesStr);
        JSONArray posArray = object.getJSONArray("root.app.pos");
        posLists = new ArrayList<>();
        for (int i = 0; i < posArray.length(); i++) {
            JSONObject item = posArray.getJSONObject(i);
            String name = item.getString("name");
            AuthEntity spot = new AuthEntity();
            spot.setMenu(1);
            spot.setId(name);
            spot.setMainTitle(name);
            spot.setVisible(true);
            spot.setHasAuth(true);
            posLists.add(spot);
            JSONArray children = item.getJSONArray("children");
            for (int j = 0; j < children.length(); j++) {
                JSONObject childItem = children.getJSONObject(j);
                AuthEntity kaidan = new AuthEntity();
                kaidan.setMenu(2);
                kaidan.setId(childItem.getString("code"));
                kaidan.setParentId(name);
                kaidan.setMainTitle(childItem.getString("name"));
                kaidan.setSubTitle(childItem.getString("desc"));
                kaidan.setVisible(true);
                kaidan.setHasAuth(true);
                posLists.add(kaidan);
            }
        }

        //市场管理
        JSONArray marketWholeArray = object.getJSONArray("root.market");
        wholeSaleLists = new ArrayList<>();
        for (int i = 0; i < marketWholeArray.length(); i++) {
            JSONObject item = marketWholeArray.getJSONObject(i);
            String name = item.getString("name");
            AuthEntity spot = new AuthEntity();
            spot.setMenu(1);
            spot.setId(name);
            spot.setMainTitle(name);
            spot.setVisible(true);
            spot.setHasAuth(true);
            wholeSaleLists.add(spot);
            JSONArray children = item.getJSONArray("children");
            for (int j = 0; j < children.length(); j++) {
                JSONObject childItem = children.getJSONObject(j);
                AuthEntity kaidan = new AuthEntity();
                kaidan.setMenu(2);
                kaidan.setId(childItem.getString("code"));
                kaidan.setParentId(name);
                kaidan.setMainTitle(childItem.getString("name"));
                kaidan.setSubTitle(childItem.getString("desc"));
                kaidan.setVisible(true);
                kaidan.setHasAuth(true);
                wholeSaleLists.add(kaidan);
            }
        }


        JSONArray wholeArray = object.getJSONArray("root.app.supplier");
        for (int i = 0; i < wholeArray.length(); i++) {
            JSONObject item = wholeArray.getJSONObject(i);
            String name = item.getString("name");
            AuthEntity spot = new AuthEntity();
            spot.setMenu(1);
            spot.setId(name);
            spot.setMainTitle(name);
            spot.setVisible(true);
            spot.setHasAuth(true);
            wholeSaleLists.add(spot);
            JSONArray children = item.getJSONArray("children");
            for (int j = 0; j < children.length(); j++) {
                JSONObject childItem = children.getJSONObject(j);
                AuthEntity kaidan = new AuthEntity();
                kaidan.setMenu(2);
                kaidan.setId(childItem.getString("code"));
                kaidan.setParentId(name);
                kaidan.setMainTitle(childItem.getString("name"));
                kaidan.setSubTitle(childItem.getString("desc"));
                kaidan.setVisible(true);
                kaidan.setHasAuth(true);
                wholeSaleLists.add(kaidan);
            }
        }

        Constant.posLists = posLists;
        Constant.wholeSaleLists = wholeSaleLists;
    }

}
